<?php

namespace app\model;

use think\Model;

class StoragelocationNumber extends Model
{

    protected $connection = 'mysql';

    protected $pk = 'id';

    protected $name = 'storagelocation_number';

    public static function getstoragelocationint($slid)
    {
        $_number = self::getnumber($slid);

        $OrderGoods = OrderGoods::where([
            'storagelocation' => $slid,
            'storagelocationint' => $_number,
            'is_complete' => 0,
        ])->find();
        if ($OrderGoods) {
            self::datainitial($slid);
            $_number = self::getnumber($slid);
        }
        
        if ($_number) {
            Storagelocation::where('id', $slid)->inc('nowquantity')->update();
            return $_number;
        }
    }

    public static function getnumber($slid)
    {
        $Storagelocationdata =  Storagelocation::find($slid);
        if ($Storagelocationdata) {
            if (empty(self::where(['slid' => $slid])->find())) {
                self::datainitial($slid);
            }
            $intdata = self::where(['slid' => $slid, 'is_complete' => 1])->order('id asc')->find()?->toArray();
            if ($intdata['storagelocationint']) {
                self::where('id', $intdata['id'])->update(['is_complete' => 0]);
                return $intdata['storagelocationint'];
            }
        }
    }

    public static function datainitial($slid)
    {
        $Storagelocationdata = Storagelocation::find($slid);
        if ($Storagelocationdata) {
            for ($i = 1; $i <= $Storagelocationdata->quantity; $i++) {
                $ogvo = OrderGoods::where([
                    'storagelocation' => $slid,
                    'storagelocationint' => $i,
                    'is_complete' => 0,
                ])->find();

                $updata['slid'] = $slid;
                $updata['storagelocationint'] = $i;

                if ($ogvo) {
                    $updata['is_complete'] = 0;
                } else {
                    $updata['is_complete'] = 1;
                }

                $slnumber = self::where(['slid' => $slid, 'storagelocationint' => $i])->find();
                if ($slnumber) {
                    self::where('id', $slnumber->id)->update(['is_complete' => $updata['is_complete']]);
                } else {
                    self::create($updata);
                }
            }
        }
    }
}
